package com.yonyou.component;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.source.PsiJavaFileImpl;
import com.intellij.psi.search.*;
import com.yonyou.biz.actions.AutoImport1;
import com.yonyou.demo.CtmDemo;
import com.intellij.psi.*;
import org.apache.commons.collections.CollectionUtils;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.util.*;
import java.io.IOException;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import java.util.stream.Collectors;

public class DelFileProcess extends Task.Backgroundable {

    private Project project;
    private  List<VirtualFile> vFiles;

    public DelFileProcess(List<VirtualFile> vFiles,@Nullable Project project, @Nls(capitalization = Nls.Capitalization.Title) @NotNull String title) {
        super(project, title);
        this.project = project;
        this.vFiles = vFiles;

    }

    @Override
    public void run(@NotNull ProgressIndicator progressIndicator) {

        List<String > logs = new ArrayList();
        List<String > logs_duoqyu = new ArrayList();

        // 设置进度条为模糊进度条
        progressIndicator.setIndeterminate(true);
        WriteCommandAction.runWriteCommandAction(project, () -> {
            List<PsiJavaFile> all=getJavaFilesInPackage(this.project,"com.yonyou.ctp.finance");

            List<PsiJavaFile> all_old=getJavaFilesInPackage(this.project,"com.yonyoucloud.fi.tlm");
            List<PsiJavaFile> all_old1=getJavaFilesInPackage(this.project,"com.yonyoucloud.fi.fusion");
            all_old.addAll(all_old1);
            //删除本地的多余类
            int count=0;
            for(PsiJavaFile file :all){
                count++;
                String log1="find::"+file.getName() ;
                final List<PsiJavaFile> collect = all_old.stream().filter(a ->removeExtension(a.getName()).equals(removeExtension(file.getName()))).collect(Collectors.toList());
                if(file.getName().contains("package-info")){
                    continue;
                }
                if(CollectionUtils.isNotEmpty(collect)){
                    for(PsiJavaFile virtualFile:collect) {
                        if(collect.size()>1){
                            logs_duoqyu.add(getPsiClassFromPsiJavaFile(virtualFile).getQualifiedName());
                        }
                        if(file.getName().equals("HolidayPrincipleEnum.class")||file.getName().equals("HolidayPrincipleEnum.java")){
                            log1 =startDel(virtualFile,log1,file);
                        }else{
                            log1 =startDel(virtualFile,log1,file);
                            break;
                        }
                    }
                }else{
                    log1= log1+"|<del_file not find >|";
                }
                log1= log1+"||process:"+count+"/"+all.size();
                logs.add(log1);
                System.out.println(log1);
            }
        });


        String filePath = "D:\\usr\\log11s.txt"; // 文件的完整路径

        writeToNonProjectFile(filePath, logs);
        String filePath1 = "D:\\usr\\log_duoyu.txt"; // 文件的完整路径
        writeToNonProjectFile(filePath1, logs_duoqyu);
        com.yonyou.ctm.ctmplugin.utils.NotificationUtil.showDialog("提示","成功");
        // 开启进度条
        progressIndicator.setIndeterminate(true);
        // 设置进度条为百分百
        progressIndicator.setFraction(1.0);
    }

    private String startDel(PsiJavaFile virtualFile, String log1,PsiJavaFile file) {
        String new_log="";
        String old=getPsiClassFromPsiJavaFile(virtualFile).getQualifiedName();
        PsiClass newsJava=getPsiClassFromPsiJavaFile(file);
        String news=newsJava.getQualifiedName();
        AutoImport1.delSt.put(old,newsJava);
        //deleteFile(project,virtualFile);
        if(!AutoImport1.del_ingoing.contains(old)){
            // 获取 Java 文件对应的 PsiDirectory
            PsiDirectory directory = virtualFile.getContainingDirectory();
            if (directory != null) {
                // 删除 Java 文件
                virtualFile.delete();
                new_log= log1+"|< del_file true del ::"+old+">|";
            }else{
                new_log= log1+"|< del_file directory is nul ::"+old+">|";
            }
        }else{
            new_log= log1+"|< del_file ingoing >|";
        }

        return new_log;
    }

    public static String removeExtension(String fileName) {
        if (fileName == null) {
            return null;
        }
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex == -1) {
            return fileName; // 文件名没有后缀
        }
        return fileName.substring(0, lastIndex); // 返回去除了后缀的文件名
    }
    public static void writeToNonProjectFile(String filePath,   List<String > logs) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, false))) {
              for(String content :logs){
                  writer.write(content);
                  writer.newLine(); // 如果需要新行，则添加
              }
            writer.flush(); // 确保所有缓冲的输出都被刷新到底层输出流
        } catch (IOException e) {
            e.printStackTrace();
            // 这里可以添加适当的错误处理逻辑
        }
    }
    public static String getFullyQualifiedName(Project project, VirtualFile virtualFile) {
        PsiManager psiManager = PsiManager.getInstance(project);
        PsiFile psiFile = psiManager.findFile(virtualFile);

        if (psiFile instanceof PsiClass) {
            PsiClass psiClass = (PsiClass) psiFile;
            return psiClass.getQualifiedName();
        }

        return null;
    }
    public static PsiClass getPsiClassFromVirtualFile(Project project, VirtualFile virtualFile) {
        PsiManager psiManager = PsiManager.getInstance(project);
        PsiFile psiFile = psiManager.findFile(virtualFile);

        if (psiFile instanceof PsiJavaFileImpl) {
            PsiJavaFileImpl psiJavaFile = (PsiJavaFileImpl) psiFile;
            return psiJavaFile.getClasses()[0]; // Assuming the file contains only one class
        }

        return null;
    }
    public Map<String, List<PsiJavaFile>> findDuplicateClasses(Project project) {
        Map<String, List<PsiJavaFile>> duplicateClassesMap = new HashMap<>();
        // 获取项目的全局搜索范围
        GlobalSearchScope scope = GlobalSearchScope.projectScope(project);

        // 遍历项目中的所有 Java 文件
        PsiFile[] files = FilenameIndex.getFilesByName(project, "java", scope);
        for (PsiFile file : files) {
            if (file instanceof PsiJavaFile) {
                PsiJavaFile javaFile = (PsiJavaFile) file;
                // 获取 Java 文件中的所有类
                for (PsiClass psiClass : javaFile.getClasses()) {
                    String className = psiClass.getName();
                    // 如果类名重复，则将该类添加到重复类列表中
                    if (className != null) {
                        List<PsiJavaFile> duplicateClasses = duplicateClassesMap.getOrDefault(className, new ArrayList<>());
                        duplicateClasses.add(javaFile);
                        duplicateClassesMap.put(className, duplicateClasses);
                    }
                }
            }
        }

        // 过滤出重名的类
        Map<String, List<PsiJavaFile>> result = new HashMap<>();
        for (Map.Entry<String, List<PsiJavaFile>> entry : duplicateClassesMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                result.put(entry.getKey(), entry.getValue());
            }
        }

        return result;
    }
    public List<PsiJavaFile> getJavaFilesInPackage(Project project, String packageName) {
        List<PsiJavaFile> javaFiles = new ArrayList<>();
        // 使用 JavaPsiFacade 获取指定包路径的 PsiPackage 对象
        JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
        PsiPackage psiPackage = javaPsiFacade.findPackage(packageName);

        if (psiPackage != null) {
            PsiDirectory[] directories = psiPackage.getDirectories();
            for (PsiDirectory directory : directories) {
                // 查找目录下的所有 Java 文件
                javaFiles.addAll(findJavaFilesInDirectory(directory));
            }
        }

        return javaFiles;
    }
    private List<PsiJavaFile> findJavaFilesInDirectory(PsiDirectory directory) {
        List<PsiJavaFile> javaFiles = new ArrayList<>();
        // 遍历目录下的所有文件
        for (PsiFile file : directory.getFiles()) {
            // 如果是 Java 文件，则添加到列表中
            if (file instanceof PsiJavaFile) {
                javaFiles.add((PsiJavaFile)file);
            }
        }
        // 递归处理子目录
        for (PsiDirectory subDirectory : directory.getSubdirectories()) {
            javaFiles.addAll(findJavaFilesInDirectory(subDirectory));
        }
        return javaFiles;
    }
    public static void deleteFile(Project project, VirtualFile fileToDelete) {
        ApplicationManager.getApplication().invokeLater(() -> {
            if (fileToDelete.isValid()) {
                try {
                    // 删除文件
                    File file = new File(fileToDelete.getPath());
                    if (file.delete()) {
                        // 删除成功，刷新文件系统
                        fileToDelete.refresh(false, false);
                    } else {
                        System.out.println(" del file error +");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static PsiClass getPsiClassFromPsiJavaFile(PsiJavaFile psiJavaFile) {
        PsiClass[] classes = psiJavaFile.getClasses();
        if (classes.length > 0) {
            // 假设文件中只有一个主类，直接返回第一个类
            return classes[0];
        }
        return null;
    }

}
